package com.fast.common.web.utils;

import com.fast.common.pojo.AuthUser;
import com.fasterxml.jackson.databind.ObjectMapper;

public class UserContextHolder {

    private ThreadLocal<AuthUser> threadLocal=null;
    private static UserContextHolder userContextHolder;

    private UserContextHolder() {
        this.threadLocal = new ThreadLocal<>();
    }

    /**
     * 用户上下文中放入信息
     *
     * @param authUser
     */
    public void setContext(String authUser) {
        try {
            threadLocal.set(new ObjectMapper().readValue(authUser, AuthUser.class));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static UserContextHolder current() {
        if (userContextHolder == null) {
            userContextHolder= new UserContextHolder();
        }
        return userContextHolder;
    }

    /**
     * 清空上下文
     */
    public void clear() {
        threadLocal.remove();
    }

    /**
     * 获取用户名
     *
     * @return
     */
    public  String getUserName() {
        return threadLocal.get().getUsername();
    }

    /**
     * 获取id
     *
     * @return
     */
    public String getUserId() {
        return threadLocal.get().getId();
    }


}
